package com.jeeccm.modules.web.jwt.service;

import com.jeeccm.modules.web.jwt.dto.ClientDTO;
import com.jeeccm.modules.web.jwt.dto.JwtConstants;
import com.jeeccm.modules.web.jwt.dto.User;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * RedisTokenService
 *
 * @author Administrator
 * @version 1.0
 * @date 2018/06/21 10:00
 */
@Component
public class RedisTokenService implements TokenService<User> {

    private RedisTemplate redisTemplate;

    @Autowired
    public void setRedis(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
        //泛型设置成Long后必须更方案改对应的序列化
        redisTemplate.setKeySerializer(new JdkSerializationRedisSerializer());
    }

    @Override
    public String createToken(String username,String jwtSecret) {
        final String token = Jwts.builder()
                .setId(username)
                .setSubject(username)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, jwtSecret)
                .compact();
        System.out.println("token=="+token);
        redisTemplate.boundValueOps(username).set(token,JwtConstants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return token;
    }

    @Override
    public boolean checkToken(ClientDTO clientDTO) {
        if(null == clientDTO){
            return false;
        }
        final String token = (String) redisTemplate.boundValueOps(clientDTO.getUserName()).get();
        if(StringUtils.isBlank(token) || !StringUtils.equals(token,clientDTO.getToken())){
            return false;
        }

        /**
         * 如果验证成功，说明此用户进行了一次有效操作，延长token的过期时间
         */
        redisTemplate.boundValueOps(clientDTO.getUserName()).expire(JwtConstants.TOKEN_EXPIRES_HOUR, TimeUnit.HOURS);
        return true;
    }

    @Override
    public ClientDTO getToken(String token, String userId) {
        return new ClientDTO.ClientBuilder(userId,token).builder();
    }

    @Override
    public boolean deleteToken(String username) {
        return redisTemplate.delete(username);
    }
}
